# -*- coding: utf-8 -*-

from sqlalchemy import func

from datetime import datetime
 
from common.order_inquiry.model import *
from common.utils import track_logging
from common.utils.db import list_object, paginate, get, upsert
from common.utils.decorator import sql_wrapper
from common.utils import exceptions as err

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def get_orderinq(id):
    return get(OrderInquiry, id)

@sql_wrapper
def upsert_orderinq(info, id=None):
    return upsert(OrderInquiry, info, id)

@sql_wrapper
def list_orderinq(query_dct):
    query, total_count = list_object(query_dct, OrderInquiry, disable_paginate=True)
    total_amount = query.statement.with_only_columns([func.sum(OrderInquiry.amount)])
    total_amount = query.session.execute(total_amount).scalar()
    query = paginate(query, query_dct)
    return query.all(), total_count, total_amount


@sql_wrapper
def create(data, chn_id=None):
    try:
        order_inquiry = OrderInquiry()
        order_inquiry.order_inquiry_no = data['order_inquiry_no']
        order_inquiry.mch_id = data['mch_id']
        order_inquiry.out_trade_no = data['out_trade_no'] 
        order_inquiry.user_id = data['user_id']
        order_inquiry.username = data['username']
        order_inquiry.amount = data['amount']
        order_inquiry.transaction_time = data['transaction_time']
        order_inquiry.notify_url = data['notify_url']
        order_inquiry.mch_create_ip = data['mch_create_ip']
        order_inquiry.sign = data['sign']
        order_inquiry.receipt = data['receipt']
        order_inquiry.notes = ''
        order_inquiry.service = data['service'] 
        order_inquiry.status = data['status'] 
        order_inquiry.notify_status = data['notify_status'] 
        order_inquiry.notify_count = data['notify_count'] 
        order_inquiry.save()
        return order_inquiry
    except Exception as e:
        _LOGGER.exception('create_order_inquiry error, %s', e)
        raise err.DataError()

@sql_wrapper
def get_order_inquiry(inq_order_no):
    return OrderInquiry.query.filter(OrderInquiry.order_inquiry_no == inq_order_no).first()

@sql_wrapper
def get_order_inquiry_by_mch(mch_id, inquiry_no):
    return OrderInquiry.query.filter(OrderInquiry.mch_id==mch_id,OrderInquiry.order_inquiry_no == inquiry_no).first()

@sql_wrapper
def push_order(id, status, operator):
    try:
        order = get_orderinq(id)
        if order:
            order.notify_status = status
            order.notify_count += 1
            order.notified_at = datetime.utcnow()
            order.operator = operator
            order.save()

    except Exception as e:
        _LOGGER.exception('push_order error, %s', e)
        raise err.DataError()
